package com.ihunanren.biz.function.service.impl;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Strings.isNullOrEmpty;

import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

import com.google.common.base.Throwables;
import com.google.common.collect.Maps;
import com.ihunanren.biz.function.Http;
import com.ihunanren.biz.function.TextMather;
import com.ihunanren.biz.function.domain.MobilePhone;
import com.ihunanren.biz.function.service.IWeixinService;

public class MobilePhoneService  implements IWeixinService<MobilePhone>{

	private final static String youdao_restful_api = "http://www.youdao.com/smartresult-xml/search.s";
	
	private final static String mobile_phone_regex = "1\\d{10}";
	
	private MobilePhone convertXml(InputStream inputStream) {
		MobilePhone bean = new MobilePhone();
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document document = db.parse(inputStream);
			
			bean.setPhone(document.getElementsByTagName("phonenum").item(0).getTextContent());
			bean.setLocation(document.getElementsByTagName("location").item(0).getTextContent());
		} catch (NullPointerException e) {
			throw new IllegalArgumentException("phone is wrong.");
		} catch (Exception e) {
			Throwables.propagate(e);
		}
		return bean;
	}

	@Override
	public List<MobilePhone> getResponse(String input) {
		checkArgument(!isNullOrEmpty(input));
		String phoneNum = TextMather.getMatherString(input, mobile_phone_regex);
		if (isNullOrEmpty(phoneNum)) {
			return null;
		}
		Http http = new Http();
		Map<String, String> m = Maps.newHashMap();
		m.put("type", "mobile");
		m.put("q", phoneNum);
		InputStream inputStream = http.doGetAsInputStream(youdao_restful_api, m);
		return Arrays.asList(convertXml(inputStream));
	}
}
